package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.base.ResponseResult;
import com.zzyl.dto.ReservationDto;
import com.zzyl.entity.Reservation;
import com.zzyl.enums.ReservationStatus;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ReservationMapper;
import com.zzyl.service.ReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.ReservationVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ReservationServiceImpl implements ReservationService {
    @Autowired
    private ReservationMapper reservationMapper;
    /**
     * 新增预约
     * @param reservationDto
     */
    @Override
    public void addReservation(ReservationDto reservationDto) {
        //类型转换，数据拷贝
        Reservation reservation = BeanUtil.copyProperties(reservationDto, Reservation.class);
        Long userId = UserThreadLocal.getUserId();
        reservation.setCreateBy(userId);
        //待报到状态
        reservation.setStatus(ReservationStatus.PENDING.getOrdinal());
        try{
            //保存
            reservationMapper.insert(reservation);
        }catch (Exception e){
            throw new BaseException("你已在当前时间段预约过");
        }
    }

    /**
     * 查询预约列表
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResponse<ReservationVo> page(int pageNum, int pageSize, String name, String phone, Integer status, Integer type, LocalDateTime startTime, LocalDateTime endTime) {
        PageHelper.startPage(pageNum,pageSize);
        Long userId = UserThreadLocal.getUserId();
        Page<Reservation> reservations = reservationMapper.findByPage(pageNum,pageSize,name,phone,status,type,userId,startTime,endTime);
        return PageResponse.of(reservations,ReservationVo.class);
    }

    /**
     * 按照时间修改过期的预约
     * @param now
     */
    @Override
    public void updateReservationStatus(LocalDateTime now) {
        reservationMapper.updateReservationStatus(now);
    }

    /**
     * 取消预约
     */
    @Override
    public void cancelReservation(Long id) {
        Reservation reservation = reservationMapper.findById(id);
        if(reservation != null){
            reservation.setStatus(ReservationStatus.CANCELED.getOrdinal());
            reservationMapper.update(reservation);
        }
    }


}
